import {Component, ElementRef, Input, ViewChild} from "@angular/core";
import {FormBuilder, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {User} from "../../../entity/User";
import {UserService} from "../../../service/userService";
import {ForbiddenNameValidator} from "../validator/forbiddenNameValidator";
import {BaseReactiveFormComponent} from "../baseReactiveForm.component";
import {AuthGuard} from "../../../service/authGuard";


@Component({
    selector: "app-login-cmp",
    templateUrl: "./login.component.html"
})
export class LoginComponent extends BaseReactiveFormComponent<User> {
    @Input() successURL: string;

    constructor(protected a_router: Router,
                public element: ElementRef,
                public route: ActivatedRoute, private authGuard: AuthGuard,
                private _userService: UserService, protected _fb: FormBuilder) {
        super(a_router, element, route, _fb, false);
        this.domainObject = new User();
        super.buildForm();
    }

    getFormErrors() {
        return {'userid': '', 'passwd': ''};
    }

    getValidationMessages() {
        return {
            'userid': {
                'required': 'Username is required.',
                // 'minlength': 'Username must be at least 4 characters long.',
                // 'maxlength': 'Username cannot be more than 64 characters long.',
                // 'forbiddenName': 'Someone named "jack" cannot be a username.'
            },
            'passwd': {
                'required': 'Password is required.'
            }
        };
    }

    _buildForm() {
        this.aForm = this.fb.group({
            'userid': [this.domainObject.userid, [
                Validators.required,
                // Validators.minLength(4),
                // Validators.maxLength(64),
                // ForbiddenNameValidator(/jack/i)
            ]
            ],
            'passwd': [this.domainObject.passwd, Validators.required],
        });
    }

    onSubmit() {
        super.onSubmit();
        this.login();
    }

    login() {
        this._userService.login(this.domainObject.userid, this.domainObject.passwd).subscribe(
            (result) => {
                // localStorage.setItem('loginUser', JSON.stringify(result.detail));
                localStorage.setItem('loginUser', JSON.stringify({userid: this.domainObject.userid, passwd: this.domainObject.passwd}));
                localStorage.setItem('token', result.token);

                if (this.domainObject.userid.includes('admin')) {
                  console.log('**** admin ****');
                  this.successURL = '/dashboard/plan';
                } else {
                  console.log('**** expert ****');
                  this.successURL = '/dashboard/task';
                }
                this.a_router.navigate([this.authGuard.backURL ? this.authGuard.backURL : this.successURL]);
            },
            err => {
                this.handleError(err);
            }
        );
    }
}
